package com.frogs.ucenter.controller;

import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Vector;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.component.cache.Cache;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.util.UrlUtil;
import com.frogs.framework.util.crypt.DESede;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.framework.web.HttpResponseUtil;
import com.frogs.system.util.ExpandCodeEnum;
import com.frogs.system.util.OpenPlatformEnum;
import com.frogs.system.util.PrivateKey;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.component.RsyncHelper;
import com.frogs.ucenter.component.UserPermissionHelper;
import com.frogs.ucenter.entity.UserBaseAccountInfo;
import com.frogs.ucenter.service.SmsService;
import com.frogs.ucenter.service.UserOpenPlatformService;
import com.frogs.ucenter.service.UserService;
import com.frogs.ucenter.util.DataCacheKey;
import com.frogs.ucenter.util.SysStatusEnum;
import com.frogs.ucenter.util.WebSiteEnum;

@Controller
public class UserOpenPlatformController extends AbsController {
	private static Logger log = LoggerFactory.getLogger(UserOpenPlatformController.class);    
	
	//开放平台：qq\weixin\weibo
	private static final String HOME = "/openplatform/index";
	private static final String LOGIN = "/openplatform/login";
	private static final String BIND = "/openplatform/bind";
	private static final String SENDVERIFY = "/openplatform/send/verify";
	private static final String SENDEMAIL = "/openplatform/send/email";
	private static final String CHECKEMAIL = "/openplatform/check/email";
	
	//蓝海
	private static final String LANHAILOGIN = "/lanhai/login";
	private static final String LANHAIREDIRECT = "/lanhai/redirect";
	
	//QQ彩贝
	private static final String CAIBEILOGIN = "/caibei/login";
	private static final String CAIBEILOGIN_VIEW = "user/redirect";
	
	private static final String MERGECART = "/openplatform/mergecart";
	private static final String LONIG_BACK_VIEW = "/user/login_back";
	private static final String MAIL_CHECK_VIEW = "/user/mail_activity";
	
	private final String sinaurl = "https://api.weibo.com/oauth2/authorize?client_id=1933251625&response_type=code&redirect_uri=http%3A%2F%2Fucenter.ehaoyao.com%2Fopenplatform%2Flogin%2F4";
	private final String qqurl = "https://graph.qq.com/oauth2.0/authorize?client_id=101067893&redirect_uri=http%3A%2F%2Fucenter.ehaoyao.com%2Fopenplatform%2Flogin%2F3&response_type=code&state=3&scope=get_user_info,add_topic,add_share";
	private final String wechaturl = "https://open.weixin.qq.com/connect/qrconnect?appid=wxa7f5d41f9b0dc6e1&redirect_uri=http%3a%2f%2fucenter.ehaoyao.com%2fopenplatform%2flogin%2f6&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
	
	@Resource
	private UserPermissionHelper userPermissionHelper;
	@Resource
	private UserOpenPlatformService userOpenPlatformService;
	@Resource
	private SmsService smsService;
	@Resource
	private UserService userService;
	@Resource(name="xmemcached")
	private Cache cache;
	@Resource
	private RsyncHelper rsyncHelper;
	
    /**
     * 进入开放平台界面进行登录操作，操作成功则开发平台自动回调我方的openPlatFormLogin接口
     * @param request
     * @param response
     * @param type
     */
    @RequestMapping(HOME+"/{type}")
    public void openPlatFormRedirect(HttpServletRequest request,HttpServletResponse response,@PathVariable("type") int type) {
		try{
			if (type == OpenPlatformEnum.SINAWEIBO.getId()) {//新浪微博
				response.sendRedirect(sinaurl);
			} else if(type == OpenPlatformEnum.QQ.getId()) {//qq联合登录
				response.sendRedirect(qqurl);
			} else if (type == OpenPlatformEnum.WECHART_QR.getId()) {//微信二维码登录
				//设置state
				String state = StringUtil.md5(String.valueOf(new Random().nextInt(10000)));
				HttpResponseUtil.setCookie(response, "state", state , ".ehaoyao.com");
				response.sendRedirect(wechaturl.replace("STATE", state));
			}
		}catch (Exception e) {
			log.error("func[openPlatFormRedirect] parameterMap[{}] exception[{} - {}] desc[fail]",//
					new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			request.setAttribute("errorMessage", e.getMessage());
		}
    }
    
    /**
     * @param request
     * @param response
     * @param type
     * 在开放平台登录成功回调的方法，此方法用户判断openid是否已绑定我方账号，如果已绑定则直接登录，如果没有绑定则跳转到绑定界面
     */
    @RequestMapping(LOGIN+"/{type}")
    public String openPlatFormLogin(HttpServletRequest request,HttpServletResponse response,@PathVariable("type") int openPlatformId, ModelMap model) {
    	try{
    		HttpRequestInfo requestInfo = new HttpRequestInfo(request);
    		String ip = requestInfo.getUserIp();
    		String code = requestInfo.getParameter("code");
    		// 微信二维码登录
    		if (openPlatformId == OpenPlatformEnum.WECHART_QR.getId()) {
    			String state = requestInfo.getParameter("state", "");
    			if (!state.equals(userPermissionHelper.getCookieVal(request, "state"))) {
    				request.setAttribute("errorMessage", "二维码失效，请重新点击微信登录");
    				return ERROR_VIEW;
    			}
    		}
			JSONObject result = userOpenPlatformService.getUserInfo(code, openPlatformId, "", ip);
			Boolean isBindOpenId = result.getJSONObject("response").getBoolean("isBindOpenId");
			String openId = result.getJSONObject("response").getString("openId");
			
			if(isBindOpenId){
				UserBaseAccountInfo user = JSONObject.toJavaObject(result.getJSONObject("response").getJSONObject("userBaseAccountInfo"), UserBaseAccountInfo.class);  //result.getJSONObject("response").get("userBaseAccountInfo");
				userPermissionHelper.setOpenPlatformCookie(request, response, user, openPlatformId , openId);
				model.put("openId", result.getJSONObject("response").getString("openId"));
				model.put("openPlatformId", openPlatformId);
				model.put("islogin", 1);
			}else{
				String nickName = result.getJSONObject("response").getString("nickName");
				model.put("openNickName", nickName);
				model.put("openId", openId);
				model.put("openPlatformId", openPlatformId);
				model.put("islogin", 0);
			}
			return LONIG_BACK_VIEW;

    	}catch (Exception e) {
    		log.error("func[openPlatFormLogin] parameterMap[{}] exception[{} - {}] desc[fail]",//
    				new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
    		request.setAttribute("errorMessage", e.getMessage());
    		return ERROR_VIEW;
    	}
    }
    
    /**
     * 第一次利用开放平台进入我们系统需绑定账号(现有账号或新的手机号)，绑定成功后进行登录
     * @param request
     * @param response
     * @param flag
     * @return
     */
    @RequestMapping(BIND+"/{flag}")
    public Map<String, Object> bindOpenPlatformLogin(HttpServletRequest request,HttpServletResponse response,@PathVariable("flag") int flag) {
    	Map<String, Object> result = new HashMap<String, Object>();
    	try{
    		HttpRequestInfo requestInfo = new HttpRequestInfo(request);
    		String ip = requestInfo.getUserIp();
    		//用户名
    		String userName = "";
    		//密码
    		String password = "";
    		//合并购物车
    		String _wt_pk_cookie = requestInfo.getParameter("_wt_pk_cookie", "");
    		//开放平台id
    		String openId = requestInfo.getParameter("openId", "");
    		//开放平台类型
    		int openPlatformId = Integer.parseInt(requestInfo.getParameter("openPlatformId","0"));
    		//绑定的email
    		String email = requestInfo.getParameter("email", "");
    		//绑定的手机
    		String phone = "";
    		//手机验证码
    		String code = "";
    		//isphpw = 1表示手机动态验证码，0表示账号的密码
    		int isphpw = 0;
    		//isRegister=1表示绑定新注册用户
    		int isRegister = Integer.parseInt(requestInfo.getParameter("isRegister","0"));
    		
    		if(flag==1){//绑定用户(包括已有用户(isRegister=0)、用户输入指定用户名和密码的注册用户(isRegister=1)、开发平台的用户(isRegister=2))
    			isphpw = Integer.parseInt(requestInfo.getParameter("isphpw","0"));
    			userName = requestInfo.getParameter("userName", "");
    			password = requestInfo.getParameter("password", "");
    			if(StringUtil.isEmpty(userName)){
    				log.error("func[bindOpenPlatformLogin] desc[用户名参数值为空]");
    				result.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.NAME_NULL.getMsg());
    				result.put(ResultParamEnum.code.getParamName(), SysStatusEnum.NAME_NULL.getCode());
    				return result;
    			}
    			if(StringUtil.isEmpty(password)){
    				log.error("func[bindOpenPlatformLogin] desc[密码参数值为空]");
    				result.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.PASSWORD_NULL.getMsg());
    				result.put(ResultParamEnum.code.getParamName(), SysStatusEnum.PASSWORD_NULL.getCode());
    				return result;
    			}
    			if(1 == isRegister){//表示绑定新注册用户
    				if(StringUtil.isEmail(userName)||StringUtil.isMobilePhone(userName)){
        				log.error("func[bindOpenPlatformLogin] desc[用户名不能是邮箱或是手机号码]");
        				result.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.REGISTER_ERR.getMsg());
        				result.put(ResultParamEnum.code.getParamName(), SysStatusEnum.REGISTER_ERR.getCode());
        				return result;
    				}
    				String confirmPassword = requestInfo.getParameter("confirmPassword", "");
    				if(!password.equals(confirmPassword)){
        				log.error("func[bindOpenPlatformLogin] desc[密码不相同]");
        				result.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.PASSWORD_ERR_SAME.getMsg());
        				result.put(ResultParamEnum.code.getParamName(), SysStatusEnum.PASSWORD_ERR_SAME.getCode());
        				return result;
    				}
    			}
    		}else if(flag==2){//绑定手机号
    			phone = requestInfo.getParameter("phone", "");
    			code = requestInfo.getParameter("code", "");
    			if(!StringUtil.isMobilePhone(phone)){
    				log.error("func[bindOpenPlatformLogin] desc[手机号参数值为空]");
    				result.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.PHONE_ERR.getMsg());
    				result.put(ResultParamEnum.code.getParamName(), SysStatusEnum.PHONE_ERR.getCode());
    				return result;
    			}
    			if(StringUtil.isEmpty(code)){
    				log.error("func[bindOpenPlatformLogin] desc[手机号动态密码参数值为空]");
    				result.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.PHONE_CODE_ERR.getMsg());
    				result.put(ResultParamEnum.code.getParamName(), SysStatusEnum.PHONE_CODE_ERR.getCode());
    				return result;
    			}
    			isRegister = 1;
    		}
			JSONObject json = userOpenPlatformService.bindUserInfo(openPlatformId, openId, userName, password, email, phone, code, isphpw, ip, isRegister,"",ExpandCodeEnum.MALL.getId());
			if (json == null) {
				result.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.NAME_PASS_ERR.getMsg());
				result.put(ResultParamEnum.code.getParamName(), SysStatusEnum.NAME_PASS_ERR.getCode());
				return result;
			}
			if (ApiResultEnum.SUCCESS.getId() != json.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				result.put(ResultParamEnum.tip.getParamName(), json.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
				result.put(ResultParamEnum.code.getParamName(), json.getJSONObject("response").getString(ResultParamEnum.code.getParamName()));
				return result;
			}
			UserBaseAccountInfo user = JSONObject.toJavaObject(json.getJSONObject("response").getJSONObject("userBaseAccountInfo"), UserBaseAccountInfo.class);  //result.getJSONObject("response").get("userBaseAccountInfo");
			if (user == null) {
				log.error("func[bindOpenPlatformLogin] desc[用户信息为空]");
				result.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.LOGIN_ERR.getMsg());
				result.put(ResultParamEnum.code.getParamName(), SysStatusEnum.LOGIN_ERR.getCode());
				return result;
			} else {
				result.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.SUCCESS.getMsg());
				result.put(ResultParamEnum.code.getParamName(), SysStatusEnum.SUCCESS.getCode());
				result.put(UserPermissionHelper.COOKIE_UID, user.getId());
			}

			
			
			userPermissionHelper.setOpenPlatformCookie(request, response, user, openPlatformId,openId);
			rsyncHelper.mergeShoppingCart(user.getId(), _wt_pk_cookie);
			return result;
    		
    	}catch (Exception e) {
    		log.error("func[bindOpenPlatformLogin] parameterMap[{}] exception[{} - {}] desc[fail]",//
    				new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
    		request.setAttribute("errorMessage", e.getMessage());
    	}
    	return result;
    }
    
    /**
     * 客户验证邮箱链接，正确则进行登录操作,被给出提示信息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(CHECKEMAIL)
    public String bindOpenPlatformLoginByEmail(HttpServletRequest request,HttpServletResponse response, ModelMap model) {
    	try{
    		HttpRequestInfo requestInfo = new HttpRequestInfo(request);
    		String ip = requestInfo.getUserIp();
    		//md5加密key，用于校验正确性
    		String key = requestInfo.getParameter("k", "");
    		//p是openId + "|" + openPlatformId + "|" + email的base64加密
    		String ooe = requestInfo.getParameter("p", "");
    		if(StringUtil.isEmpty(key) || StringUtil.isEmpty(ooe)){
    			log.error("func[bindOpenPlatformLoginByEmail] desc[邮箱验证失败,参数值为空]");
				model.put(ResultParamEnum.tip.getParamName(), "抱歉，邮箱验证失败");
				model.put(ResultParamEnum.code.getParamName(), 0);
				return MAIL_CHECK_VIEW;
    		}
    		String decodeStr = StringUtil.base64Decode(ooe);
    		String[] array = decodeStr.split("\\|");
    		if(array.length!=3){
    			log.error("func[bindOpenPlatformLoginByEmail] desc[邮箱验证失败,参数值不对]");
    			model.put(ResultParamEnum.tip.getParamName(), "抱歉，邮箱验证失败");
    			model.put(ResultParamEnum.code.getParamName(), 0);
				return MAIL_CHECK_VIEW;
    		}
    		//开放平台id
    		String openId = array[0];
    		//开放平台类型
    		int openPlatformId = Integer.parseInt(array[1]);
    		//绑定的email
    		String email = array[2];
    		String cacheKey = (String) cache.get(DataCacheKey.openPlatformActivateEmailMapkey + StringUtil.md5(openId + openPlatformId + email));
    		log.info("func[bindOpenPlatformLoginByEmail] openid["+openId+"] openPlatformId["+openPlatformId+"] email["
    		+email+"] cacheKey["+cacheKey+"] key["+key+"] desc[check]");
    		if(StringUtil.isEmpty(cacheKey) || !key.equalsIgnoreCase(cacheKey)){
    			log.error("func[bindOpenPlatformLoginByEmail] desc[邮箱验证失败,key值不相同]");
    			model.put(ResultParamEnum.tip.getParamName(), "抱歉，邮箱验证失败");
    			model.put(ResultParamEnum.code.getParamName(), 0);
				return MAIL_CHECK_VIEW;
    		}
    		JSONObject json = userOpenPlatformService.bindUserInfo(openPlatformId, openId, "", "", email, "", "", 0, ip, 1,"",ExpandCodeEnum.MALL.getId());
    		UserBaseAccountInfo user = JSONObject.toJavaObject(json.getJSONObject("response").getJSONObject("userBaseAccountInfo"), UserBaseAccountInfo.class);  //result.getJSONObject("response").get("userBaseAccountInfo");
    		if (user == null) {
    			log.error("func[bindOpenPlatformLoginByEmail] desc[用户信息为空]");
    			model.put(ResultParamEnum.tip.getParamName(), "抱歉，邮箱验证失败");
    			model.put(ResultParamEnum.code.getParamName(), 0);
    			return MAIL_CHECK_VIEW;
    		} else {
    			model.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.SUCCESS.getMsg());
    			model.put(ResultParamEnum.code.getParamName(), SysStatusEnum.SUCCESS.getCode());
    			model.put("nickName", user.getNickName());
    		}
    		userPermissionHelper.setOpenPlatformCookie(request, response, user, openPlatformId , openId);
    		return MAIL_CHECK_VIEW;
    		
    	}catch (Exception e) {
    		log.error("func[bindOpenPlatformLoginByEmail] parameterMap[{}] exception[{} - {}] desc[fail]",//
    				new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
    		request.setAttribute("errorMessage", e.getMessage());
    	}
    	return MAIL_CHECK_VIEW;
    }
    
    /**
     * 注意：
     * 1.彩贝对接流程见 doc\需求\1.3.1\彩贝\G2技术文档--02.09更新 (1)\G2技术文档--02.09更新\QQ彩贝商家接入指引0209更新.ppt
     * 2.彩贝CPS的采集和统计主要是商城在做
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(CAIBEILOGIN)
    public String bindOpenPlatformLoginByCaibei(HttpServletRequest request,HttpServletResponse response, ModelMap model){
    	try{
	    	HttpRequestInfo requestInfo = new HttpRequestInfo(request);
	    	/*渠道id 好药师自己定义的*/
	    	Integer openPlatformId= OpenPlatformEnum.CAIBEI.getId();
	    	
	    	/* 跟Acct一致 */
	    	String openId = requestInfo.getParameter("OpenId");
	    	/* 跟用户QQ帐户一一对应的字符串，该字段是商户作为识别帐户的唯一依据 */
	    	String acct = requestInfo.getParameter("Acct");
	    	/* 用于传递是否QQ会员等信息，请忽略*/
	    	String clubInfo = requestInfo.getParameter("ClubInfo");
	    	/* 联合登录的跳转来源：
				1.当用户在合作伙伴网站直接登录时，LoginFrom=[商户id],商户id由彩贝平台分配，如乐淘，则LoginFrom=letao等。
				2.当用户在彩贝平台直接跳转到商户时候：LoginFrom=caibei。
	    	 */
	    	String loginFrom = requestInfo.getParameter("LoginFrom");
	    	
	    	/* ViewInfo是一个结构化字符串，解析后的结果是：
				array(
				    'ShowMsg'  => 展示在页面顶部，给用户提示语, 
				    'NickName' => QQ昵称,
				    'CBPoints' => 用户剩余彩贝积分,
				    'CBBonus'    => 返利比率
				)
	    	 */
	    	String viewInfo = requestInfo.getParameter("ViewInfo");
	    	/* 联合登录完成后要跳转的的Url，若该值没有输入，则商户处理联合登录后跳转商户站点首页即可，否则商户则必须跳转到该Url指定的页面。*/
	    	String url = requestInfo.getParameter("Url");
	    	/* 请忽略*/
	    	String attach = requestInfo.getParameter("Attach");
	    	/* 数字签名串 该值是对联合登录各个字段进行签名后的32位的字符串。*/
	    	String vkey = requestInfo.getParameter("Vkey","");
	    	/* 字符串格式的时间戳，格式为20090724120401*/
	    	String ts = requestInfo.getParameter("Ts");
	    	/* 上线前需要QQ彩贝给到正式的key*/
	    	String key1 = "PGtwffwoKL4IoGO886dCcN2QSSMMXUFO";
	    	/* 上线前需要QQ彩贝给到正式的key*/
	    	String key2 = "B0mRoTgaFjS62Hd9NrL1fMR0GEWFACvd";
	
	    	String raw_string = this.sortParamsForCaibei(request);//new StringBuilder(acct).append(attach).append(clubInfo).append(loginFrom).append(openId).append(ts).append(url).append(viewInfo);
	    	String md5Vkey = StringUtil.md5(StringUtil.md5(raw_string.toString()+key1).toLowerCase()+key2).toLowerCase();
	    	
	    	String ip = requestInfo.getUserIp();
	    	
	    	HashMap<String,String> viewInfoMap = decodeViewInfoForCaibei(viewInfo);
	    	if( vkey.equals("") || !md5Vkey.equals(vkey) ) {
	    	    //如果vkey检测不通过，那么跳转到出错页
	    		log.error("func[bindOpenPlatformLoginByCaibei] openPlatformId[{}] ts[{}] url[{}] viewInfo[{}] loginFrom[{}] openId[{}] md5vkey[{}] vkey[{}] error! ",//
	    				new Object[] {openPlatformId,ts ,url,viewInfo,loginFrom,openId,md5Vkey ,vkey });
	    		request.setAttribute("errorMessage", "vkey error!");
	    		return ERROR_VIEW;
	    	}
	    	
	    	JSONObject jsonInfo = userOpenPlatformService.getUserInfo("", OpenPlatformEnum.CAIBEI.getId(), openId, ip);
	    	Boolean isBindOpenId = jsonInfo.getJSONObject("response").getBoolean("isBindOpenId");
			UserBaseAccountInfo user;
			if(!isBindOpenId){
	    		//彩贝暂时合并到QQ上
	    		JSONObject json = userOpenPlatformService.bindUserInfo(OpenPlatformEnum.CAIBEI.getId(), openId, "", "", "", "", "", 0, ip, 1,viewInfoMap.get("NickName"), ExpandCodeEnum.CAIBEI.getId());
	    		user = JSONObject.toJavaObject(json.getJSONObject("response").getJSONObject("userBaseAccountInfo"), UserBaseAccountInfo.class);  //result.getJSONObject("response").get("userBaseAccountInfo");
	    	}
	    	else{
	    		user = JSONObject.toJavaObject(jsonInfo.getJSONObject("response").getJSONObject("userBaseAccountInfo"), UserBaseAccountInfo.class);  //result.getJSONObject("response").get("userBaseAccountInfo");
	    	}
	    	this.setCookieForCaibei(viewInfoMap, attach,openId, response);
			userPermissionHelper.setOpenPlatformCookie(request, response, user, OpenPlatformEnum.CAIBEI.getId(),openId);
	
			model.put("nextPath",url);
			return CAIBEILOGIN_VIEW;
    	}
    	catch (Exception e) {
    		log.error("func[bindOpenPlatformLoginByEmail] parameterMap[{}] exception[{} - {}] desc[fail]",//
    				new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
    		request.setAttribute("errorMessage", e.getMessage());
    		return ERROR_VIEW;
    	}
    }
    
    /**
     * @param viewInfoMap
     * @param attach 统计字段，下单后需要回传
     */
    private void setCookieForCaibei(HashMap<String,String> viewInfoMap , String attach,String openId , HttpServletResponse response ){
    	//point:用户可使用的彩贝积分，根据需要保存cookie
    	//bonus:购买后的返利比率，根据需要保存cookie
    	HttpResponseUtil.setCookie(response, "point", viewInfoMap.get("CBPoints"), WebSiteEnum.ROOT.getUrl(), "/");
    	HttpResponseUtil.setCookie(response, "bonus", viewInfoMap.get("CBBonus"), WebSiteEnum.ROOT.getUrl(), "/");
    	HttpResponseUtil.setCookie(response, "attach", attach, WebSiteEnum.ROOT.getUrl(), "/");
    }

    private HashMap<String,String> decodeViewInfoForCaibei(String viewInfo){
    	String[] arr1 = viewInfo.split("&");
    	String[] arr2 = {};
    	HashMap<String,String> viewinfoMap = new HashMap<String,String>();
    	int arrLen = arr1.length;
    	for(int i=0 ; i<arrLen ; i++) {
    	    arr2 = arr1[i].split("=");
    	    if( arr2.length > 1 ) {
    	        //这里的编码请自行指定
    	        viewinfoMap.put( arr2[0] , UrlUtil.decode(arr2[1],"gbk"));
    	    }
    	}
    	return viewinfoMap;
    }
    
    /**
     * 彩贝对接-参数值进行排序
     * @param request
     * @return
     */
    private String sortParamsForCaibei(HttpServletRequest request){
    	Enumeration params = request.getParameterNames();
    	Vector vc = new Vector();
    	while( params.hasMoreElements() ) {
    	    vc.add( (String)params.nextElement() );
    	}
    	String[] paramArr = (String[])vc.toArray(new String[1]);
    	int paramLen = paramArr.length;
    	int tempLen  = paramLen - 1;
    	int i,j;
    	String tempStr = "";
    	for(i=0 ; i<tempLen ; i++) {
    	    for(j=i+1 ; j<paramLen ; j++) {
    	        if( paramArr[i].compareTo( paramArr[j] ) > 0 ) {
    	            tempStr = paramArr[i];
    	            paramArr[i] = paramArr[j];
    	            paramArr[j] = tempStr;
    	        }
    	    }
    	}

    	String rawMd5Str = "";
    	for(i=0 ; i<paramLen ; i++) {
    	    if( paramArr[i].compareTo("Vkey") != 0 ) { //签名串不要Vkey这个参数
    	        rawMd5Str += request.getParameter(paramArr[i]);
    	    }
    	}
    	return rawMd5Str;
    }

    /**
     * 蓝海之略绑定接口
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(LANHAILOGIN)
    public Map<String, Object> bindOpenPlatformLoginByLanhai(HttpServletRequest request,HttpServletResponse response) {
    	Map<String, Object> result = new HashMap<String, Object>();
    	try{
    		HttpRequestInfo requestInfo = new HttpRequestInfo(request);
    		//desede加密后的字符串key，用于校验正确性
    		String key = requestInfo.getParameter("key", "");
    		//蓝海用户名
    		String userName = requestInfo.getParameter("userName", "");
    		//客户端ip
    		String ip = requestInfo.getParameter("ip", requestInfo.getUserIp());
    		
    		if(StringUtil.isEmpty(userName) || StringUtil.isEmpty(key)){
    			log.error("func[bindOpenPlatformLoginByLanhai] desc[蓝海之略用户名或是加密串参数值为空]");
    			result.put(ResultParamEnum.tip.getParamName(), "用户名或加密串参数值为空");
    			result.put(ResultParamEnum.code.getParamName(), 0);
    			return result;
    		}
    		
    		if(StringUtil.isEmpty(ip)){
    			log.error("func[bindOpenPlatformLoginByLanhai] desc[IP地址不能为空]");
    			result.put(ResultParamEnum.tip.getParamName(), "IP地址不能为空");
    			result.put(ResultParamEnum.code.getParamName(), 0);
    			return result;
    		}
    		
    		String decodeStr = DESede.createDecryptor(key, PrivateKey.LANHAI_PRIVATE_KEY.getValue());
    		
    		if(!(UrlUtil.decode(decodeStr, "utf-8")).equals(userName)){
    			log.error("func[bindOpenPlatformLoginByLanhai] desc[加密结果不一致]");
    			result.put(ResultParamEnum.tip.getParamName(), "加密结果不一致");
    			result.put(ResultParamEnum.code.getParamName(), 0);
    			return result;
    		}
    		
    		JSONObject jsonInfo = userOpenPlatformService.getUserInfo("", OpenPlatformEnum.LANHAI.getId(), userName, ip);
    		Boolean isBindOpenId = jsonInfo.getJSONObject("response").getBoolean("isBindOpenId");
    		UserBaseAccountInfo user;
    		if(isBindOpenId){
        		user = JSONObject.toJavaObject(jsonInfo.getJSONObject("response").getJSONObject("userBaseAccountInfo"), UserBaseAccountInfo.class);  //result.getJSONObject("response").get("userBaseAccountInfo");
    		} else {
	    		JSONObject json = userOpenPlatformService.bindUserInfo(OpenPlatformEnum.LANHAI.getId(), userName, "", "", "", "", "", 0, ip, 1,"",ExpandCodeEnum.LANHAI.getId());
	    		user = JSONObject.toJavaObject(json.getJSONObject("response").getJSONObject("userBaseAccountInfo"), UserBaseAccountInfo.class);  //result.getJSONObject("response").get("userBaseAccountInfo");
    		}
    		if (user == null) {
    			log.error("func[bindOpenPlatformLoginByLanhai] desc[用户信息为空]");
    			result.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.LOGIN_ERR.getMsg());
    			result.put(ResultParamEnum.code.getParamName(), SysStatusEnum.LOGIN_ERR.getCode());
    			return result;
    		} else {
    			result.put("hysusername", user.getAccountName());
    			result.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.SUCCESS.getMsg());
    			result.put(ResultParamEnum.code.getParamName(), SysStatusEnum.SUCCESS.getCode());
    		}
    		return result;
    	}catch (Exception e) {
    		log.error("func[bindOpenPlatformLoginByLanhai] parameterMap[{}] exception[{} - {}] desc[fail]",//
    				new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
    		request.setAttribute("errorMessage", e.getMessage());
    	}
    	return result;
    }
   
    /**
     * 蓝海之略重定向接口
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(LANHAIREDIRECT)
    public String lanHaiRedirect(HttpServletRequest request,HttpServletResponse response) {
    	Map<String, Object> result = new HashMap<String, Object>();
    	try{
    		HttpRequestInfo requestInfo = new HttpRequestInfo(request);
    		//desede加密后的字符串key，用于校验正确性
    		String key = requestInfo.getParameter("key", "");
    		//蓝海用户名
    		String userName = requestInfo.getParameter("userName", "");
    		//跳转url
    		String subjectUrl = requestInfo.getParameter("subjectUrl", "");
    		
    		String ip = requestInfo.getParameter("ip", requestInfo.getUserIp());
    		
    		if(StringUtil.isEmpty(userName) || StringUtil.isEmpty(key)){
    			log.error("func[lanHaiRedirect] desc[蓝海之略用户名或是加密串参数值为空]");
    			result.put(ResultParamEnum.tip.getParamName(), "用户名或加密串参数值为空");
    			result.put(ResultParamEnum.code.getParamName(), 0);
    			return ERROR_VIEW;
    		}
    		if(StringUtil.isEmpty(subjectUrl)){
    			log.error("func[lanHaiRedirect] desc[url不能为空]");
    			result.put(ResultParamEnum.tip.getParamName(), "url不能为空");
    			result.put(ResultParamEnum.code.getParamName(), 0);
    			return ERROR_VIEW;
    		}
    		
    		if(StringUtil.isEmpty(ip)){
    			log.error("func[lanHaiRedirect] desc[IP地址不能为空]");
    			result.put(ResultParamEnum.tip.getParamName(), "IP地址不能为空");
    			result.put(ResultParamEnum.code.getParamName(), 0);
    			return ERROR_VIEW;
    		}
    		
    		String encodeStr = userName + subjectUrl;
    		String decodeStr = DESede.createDecryptor(key, PrivateKey.LANHAI_PRIVATE_KEY.getValue());
    		
    		if(!(UrlUtil.decode(decodeStr, "utf-8")).equals(encodeStr)){
    			log.error("func[lanHaiRedirect] desc[加密结果不一致]");
    			result.put(ResultParamEnum.tip.getParamName(), "加密结果不一致");
    			result.put(ResultParamEnum.code.getParamName(), 0);
    			return ERROR_VIEW;
    		}
    		
    		JSONObject jsonInfo = userOpenPlatformService.getUserInfo("", OpenPlatformEnum.LANHAI.getId(), userName, ip);
    		Boolean isBindOpenId = jsonInfo.getJSONObject("response").getBoolean("isBindOpenId");
    		UserBaseAccountInfo user;
    		if(isBindOpenId){
    			user = JSONObject.toJavaObject(jsonInfo.getJSONObject("response").getJSONObject("userBaseAccountInfo"), UserBaseAccountInfo.class);  //result.getJSONObject("response").get("userBaseAccountInfo");
    		} else {
    			result.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.LOGIN_ERR.getMsg());
    			result.put(ResultParamEnum.code.getParamName(), SysStatusEnum.LOGIN_ERR.getCode());
    			return ERROR_VIEW;
    		}
    		if (user == null) {
    			result.put(ResultParamEnum.tip.getParamName(), SysStatusEnum.LOGIN_ERR.getMsg());
    			result.put(ResultParamEnum.code.getParamName(), SysStatusEnum.LOGIN_ERR.getCode());
    			return ERROR_VIEW;
    		}
    		userPermissionHelper.setOpenPlatformCookie(request, response, user, OpenPlatformEnum.LANHAI.getId(),"");
    		response.sendRedirect(subjectUrl);
    		return "";
    	}catch (Exception e) {
    		log.error("func[lanHaiRedirect] parameterMap[{}] exception[{} - {}] desc[fail]",//
    				new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
    		request.setAttribute("errorMessage", e.getMessage());
    		return ERROR_VIEW;
    	}
    }
    
    /**
     * 绑定手机，发送手机验证码
     * @param request
     * @param response
     * @param type
     * @return
     */
    @RequestMapping(SENDVERIFY)
    public JSONObject sendOpenPlatformVerify(HttpServletRequest request,HttpServletResponse response){
    	HttpRequestInfo requestInfo = new HttpRequestInfo(request);
    	JSONObject json = new JSONObject();
		//绑定的手机
		String phone = requestInfo.getParameter("phone", "");
		String openId = requestInfo.getParameter("openId", "");
		int openPlatformId = requestInfo.getIntParameter("openPlatformId", 0);
		String imgCode = requestInfo.getParameter("imgCode", "");
		try {
			String msg = checkValidateCode(imgCode, request, response);
			if (!"success".equals(msg)) {
				json.put(ResultParamEnum.tip.getParamName(), msg);
				json.put(ResultParamEnum.code.getParamName(), SysStatusEnum.VALIDATE_CODE_ERR.getCode());
				return json;
			}
			if(StringUtil.isEmpty(phone)){
				json.put("code", 0);
				json.put("tip", "手机号码不能为空");
				return json;
			} 
			if(openPlatformId != OpenPlatformEnum.QQ.getId() && openPlatformId != OpenPlatformEnum.SINAWEIBO.getId() 
					&& openPlatformId != OpenPlatformEnum.WECHART_QR.getId()){
				json.put("code", 0);
				json.put("tip", "平台类型不正确");
				return json;
			}
	    	if(StringUtil.isEmpty(openId)){
	    		json.put("code", 0);
	    		json.put("tip", "openId不能为空");
	    		return json;
	    	} 
			
	    	//判断是否登录开放平台，如果没有登录是不能发送手机验证码的
			if(cache.get(DataCacheKey.openPlatformInfoMapkey + "_" + openPlatformId + "_" + openId) == null){
				json.put("code", 0);
				json.put("tip", "开放平台登录已过期，请重新登录开放平台");
	    		return json;
			};
			boolean flag = false;
			
			flag = userService.verifyPhone(phone);
		
			if(!flag){
				json.put("code", 0);
				json.put("tip", "该手机号已经被使用过，请换另一个手机号");
				return json;
			}
			//防止频繁调用发送短信接口，如果缓存中已经存在，则不继续发送，缓存时间为20秒。
			if (cache.get(DataCacheKey.openPlatformVerifyRateMapkey + openPlatformId + phone) != null) {
				json.put("code", 0);
				json.put("tip", "请求已发送，请勿频繁请求");
				return json;
			}
			Boolean result = smsService.sendOpenPlatformVerify(phone, openPlatformId, 120);
			if(!result){
				json.put("code", 0);
				json.put("tip", "发送短信验证码失败，请重新发送");
				cache.remove(DataCacheKey.openPlatformVerifyRateMapkey + openPlatformId + phone);
				return json;
			}
			
			cache.put(DataCacheKey.openPlatformVerifyRateMapkey + openPlatformId + phone, "sendVerify", 2);
			json.put("code", 1);
			json.put("tip", "发送短信验证码成功，稍后请留意短信");
			return json;
		} catch (Exception e) {
    		log.error("func[sendOpenPlatformVerify] parameterMap[{}] exception[{} - {}] desc[fail]",//
    				new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
    		request.setAttribute("errorMessage", e.getMessage());
			json.put("code", 0);
			json.put("tip", "发送验证码失败");
			return json;
		}
    }
    /**
     * 绑定邮箱，发送邮箱验证信息
     * @param request
     * @param response
     * @param type
     * @return
     */
    @RequestMapping(SENDEMAIL)
    public JSONObject sendOpenPlatformEmail(HttpServletRequest request,HttpServletResponse response){
    	HttpRequestInfo requestInfo = new HttpRequestInfo(request);
    	JSONObject json = new JSONObject();
    	//绑定的手机
    	String email = requestInfo.getParameter("email", "");
    	String openId = requestInfo.getParameter("openId", "");
    	int openPlatformId = requestInfo.getIntParameter("openPlatformId", 0);
    	
    	if(StringUtil.isEmpty(email)){
    		json.put("code", 0);
    		json.put("tip", "email不能为空");
    		return json;
    	} 
    	if(StringUtil.isEmpty(openId)){
    		json.put("code", 0);
    		json.put("tip", "openId不能为空");
    		return json;
    	} 
    	if(0 == openPlatformId){
    		json.put("code", 0);
    		json.put("tip", "开放平台ID不能为空");
    		return json;
    	} 
    	//判断是否登录开放平台，如果没有登录是不能发生邮件的
		if(cache.get(DataCacheKey.openPlatformInfoMapkey + "_" + openPlatformId + "_" + openId) == null){
			json.put("code", 0);
			json.put("tip", "开放平台登录已过期，请重新登录开放平台");
    		return json;
		};
		Boolean flag = false;
		try {
			flag = userService.verifyEmail(email);
		} catch (Exception e) {
    		log.error("func[sendOpenPlatformEmail] parameterMap[{}] exception[{} - {}] desc[fail]",//
    				new Object[] { request.getParameterMap(), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
    		request.setAttribute("errorMessage", e.getMessage());
			json.put("code", 0);
			json.put("tip", "发送邮箱验证码失败");
			return json;
		}
		if(!flag){
			json.put("code", 0);
			json.put("tip", "该邮箱已经被使用过，请换另一个邮箱");
			return json;
		}
    	//防止频繁调用发送邮件接口，如果缓存中已经存在，则不继续发送，缓存时间为20秒。
    	if (cache.get(DataCacheKey.openPlatformEmailRateMapkey + openPlatformId + email) != null) {
    		log.error("频繁调用发送邮件接口"+email);
    		json.put("code", 0);
    		json.put("tip", "请求已发送，请勿频繁请求");
    		return json;
    	}
    	Boolean result = userOpenPlatformService.sendActivataAccountEmail(openId, openPlatformId, email);
    	if(!result){
    		json.put("code", 0);
    		json.put("tip", "发送邮箱验证码失败，请重新发送");
    		cache.remove(DataCacheKey.openPlatformEmailRateMapkey + openPlatformId + email);
    		return json;
    	}
    	
    	cache.put(DataCacheKey.openPlatformEmailRateMapkey + openPlatformId + email, "sendEmail", 2);
    	json.put("code", 1);
    	json.put("tip", "发送邮箱验证码成功，稍后请登录邮箱进行验证");
    	return json;
    }
    /**
     * 登录成功，前端异步调用合并购物车
     * @param request
     * @param response
     * @param type
     * @return
     */
    @RequestMapping(MERGECART)
    public void mergeShoppingCart(HttpServletRequest request,HttpServletResponse response){
    	HttpRequestInfo requestInfo = new HttpRequestInfo(request);
    	//用户ID
    	int userId = requestInfo.getIntParameter("userId",0);
    	String _wt_pk_cookie = requestInfo.getParameter("_wt_pk_cookie", "");
    	
    	rsyncHelper.mergeShoppingCart(userId, _wt_pk_cookie);
    }
    
    
}
